import axios from 'axios'
import router from '@/router'

import { ElMessage } from 'element-plus'

import { useUserStore } from '@/stores'

const baseURL = 'https://big-event-vue-api-t.itheima.net'

const instance = axios.create({
  baseURL,
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    if (userStore.token) {
      // 设置请求头信息
      config.headers.Authorization = userStore.token
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    if (res.data.code === 0) {
      return res
    }
    // 抛出错误信息
    ElMessage.error(res.data.message || '服务异常')
    return Promise.reject(res.data)
  },
  (err) => {
    const res = err.response
    ElMessage.error(res.data.message || '服务异常')
    // 401特殊处理
    if (res?.status === 401) {
      router.push('/login')
    }
    // 默认情况
    return Promise.reject(err)
  }
)

export default instance
export { baseURL }
